package message

import (
	"context"
	"wave-service/server/app/common/response"
	"wave-service/server/app/internal/svc"
	"wave-service/server/app/internal/types"
	"wave-service/server/app/validate"

	"github.com/zeromicro/go-zero/core/logx"
)

type MessageListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewMessageListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MessageListLogic {
	return &MessageListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MessageListLogic) MessageList(req *types.MessageListRequest) (resp *types.MessageListResponse, err error) {
	errStr := validate.Verify(req)
	if errStr != "" {
		return nil, response.Error(400, errStr)
	}

	messages, err := l.svcCtx.MessagesModel.FindList(req.ChannelId)
	if err != nil {
		return nil, err
	}
	var msgs []types.Message
	for _, m := range messages {
		msg := types.Message{
			Id:        m.Id,
			ChannelId: m.ChannelId,
			VisitorId: m.VisitorId,
			Type:      m.Tp,
			Content:   m.Content.String,
			CreatedAt: m.CreatedAt.Format("2006-01-02 15:04:05"),
		}
		msgs = append(msgs, msg)
	}

	return &types.MessageListResponse{
		List: msgs,
	}, nil
}
